package com.ww.netty.basic;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ww.juc.futureandcallable.GuavaFutureDemo;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;

public class NettyDiscardServer {
	
	private static Logger log = LoggerFactory.getLogger(GuavaFutureDemo.class);

    private final int serverPort;

    ServerBootstrap b = new ServerBootstrap();

    public NettyDiscardServer(int port) {
        this.serverPort = port;
    }

    public void runServer() {
        // 创建反应器线程组
        NioEventLoopGroup bossLoopGroup = new NioEventLoopGroup(1);
        NioEventLoopGroup workerLoopGroup = new NioEventLoopGroup();

        try {
            // 设置反应器线程组
            b.group(bossLoopGroup, workerLoopGroup);
            // 设置nio类型的通道
            b.channel(NioServerSocketChannel.class);
            // 设置监听端口
            b.localAddress(serverPort);
            // 设置通道的参数
            b.option(ChannelOption.SO_KEEPALIVE, true);
            b.option(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT);
            // 装配子通道流水线
            b.childHandler(new ChannelInitializer<SocketChannel>() {
                // 有连接到达时会创建一个通道
                @Override
                protected void initChannel(SocketChannel socketChannel) throws Exception {
                    // 流水线管理子通道中的Handler处理器
                    // 向子通道流水线添加一个handler处理器
                    socketChannel.pipeline().addLast(new NettyDiscardHandler());
                }
            });
            // 开始绑定服务器
            // 通过调用sync同步方法阻塞知道绑定成功
            ChannelFuture channelFuture = b.bind().sync();
            log.info("服务器启动成功，监听端口：" + channelFuture.channel().localAddress());
            // 等待通道关闭的异步任务结束
            // 服务器监听通道一直等待通道关闭的异步任务结束
            ChannelFuture closeFuture = channelFuture.channel().closeFuture();
            closeFuture.sync();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            // 关闭EventLoopGroup
            // 释放掉所有资源包括创建的线程
            workerLoopGroup.shutdownGracefully();
            bossLoopGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) {
        int port = 28888;
        new NettyDiscardServer(port).runServer();
    }
}
